package com.zlt.dao.Impl;

import com.zlt.dao.OfferDao;
import com.zlt.entity.Offer;
import com.zlt.entity.ReOffer;
import com.zlt.util.JDBCUtil;
import com.zlt.util.SqlUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class OfferDaoImpl implements OfferDao {

    JdbcTemplate template = new JdbcTemplate(JDBCUtil.getDataSource());

    public int insertOffer(Offer offer) {
        return SqlUtil.insert(offer);
    }


    @Override
    public Long selectOfferCountByCid(Integer cid) {
        String sql="select count(*) c from offer where cid=?";
        return (Long) SqlUtil.select(sql,cid).get(0).get("c");
    }

    @Override
    public List<Offer> selectAllOffer(Integer page, Long limit, Integer cid) {
        String sql="select oid,send_time,offer.state,valid_time,offer.cid,offer.uid,note,content,url,user.username,company.cname from offer left join user on user.uid=offer.uid left join company on offer.cid=company.cid where offer.state <> 4 and company.cid=? limit ?,?";
        return SqlUtil.select(Offer.class,sql,cid,(page-1)*limit,limit);
    }

    @Override
    public int updateOfferState(Integer oid,Integer state) {
        String sql="update offer set state=? where oid=?";
        return SqlUtil.update(sql,state,oid);
    }

    @Override
    public int updateOffer(String sql, Object[] params) {
        System.out.println(sql+"  "+params.toString());
        return SqlUtil.update(sql,params);
    }

    @Override
    public int chickOffer(String username,String oid, String state) {
        String sql = "UPDATE offer SET state = ? WHERE oid = ? AND uid = ( SELECT uid FROM user WHERE username = ? )";
        return template.update(sql,state,oid,username);
    }

    @Override
    public List<ReOffer> show(String username) {
        String sql = "SELECT o.oid, o.send_time AS sendTime, o.state, o.valid_time AS validTime, c.cname AS company, o.note AS note, o.content AS content FROM offer AS o,company AS c WHERE o.cid=c.cid AND o.uid = ( SELECT uid FROM user WHERE username = ? ) AND o.state != 4";
//        return template.query(sql,BeanPropertyRowMapper.newInstance(ReOffer.class),username);
        return template.query(sql, new BeanPropertyRowMapper(ReOffer.class),username);
    }

}
